﻿#region Used Namespaces

using System.Collections.Generic;
using System.Linq;
using ContactPrinter.Logic.Interfaces;
using ContactPrinter.Model;
using ContactPrinter.Model.Interfaces;
using Google.Contacts;
using Google.GData.Client;
using Google.GData.Contacts;
using Group = Google.Contacts.Group;

#endregion

namespace ContactPrinter.Logic
{
    public class GoogleContactService : IContactService
    {
        private const string contactServiceId = "contact-printer-sw";

        private readonly ContactsRequest contactsRequest;

        public GoogleContactService(string userName, string password)
        {
           var requestSettings = new RequestSettings(contactServiceId, userName, password) { AutoPaging = true };
           contactsRequest = new ContactsRequest(requestSettings);
        }

        public IEnumerable<IGroup> GetGroups()
        {
            Feed<Group> groups = contactsRequest.GetGroups();
            return groups.Entries.Select(group => new Model.Group(group.Id, group.Title));
        }

        public IEnumerable<IContact> GetAllContactsFromGroup(string group)
        {          
            var query = new ContactsQuery(ContactsQuery.CreateContactsUri("default")) {Group = @group};

            Feed<Contact> contacts = contactsRequest.Get<Contact>(query);
            return contacts.Entries.Select(contact => new GoogleContact(contact));
        }
    }
}